package com.qike.baoxiu.controller;

import com.alibaba.fastjson.JSONObject;
import com.qike.baoxiu.tools.AuthUtil;
import com.qike.baoxiu.tools.URIUtil;
import com.qike.baoxiu.tools.WxConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: huadongexcel
 * @author: Eric
 * @create: 2020-06-09 12:21
 */
@RestController
@CrossOrigin
@Api(description = "微信接口")
@RequestMapping("/wechat")
public class WeChatController {


    @ApiOperation("鉴权")
    @GetMapping("/auth")
    public String auth() {
        System.out.println("进入到微信页面自定义方法地址...");
        //拼接微信网页授权地址
        String redirectURL = String.format(WxConstant.WX_CONNECT_OAUTH2_AUTHORIZE_URL, WxConstant.WX_APP_ID, URIUtil.encodeURIComponent(WxConstant.REQUEST_URL),
                WxConstant.WX_SNSAPI_BASE, WxConstant.WX_STATE);
//        System.out.println("【微信网页授权】获取redirectURL,redirectURL={}", redirectURL);
        return  redirectURL;
    }

    //回调地址调用
    @ApiOperation("获取用户信息")
    @GetMapping("/userinfo")
    public JSONObject userinfo(HttpServletRequest req){
        JSONObject userInfo = null;
//        log.info("进入到回调地址...");
        String code=req.getParameter("code");
//        log.info("【回调地址】获取的code值为{}",code);
        try {
            if(!"authdeny".equals(code)){
                //拼装获取access_token的url请求
                String tokenUrl = WxConstant.WX_GET_TOKEN_URL.replace("ID", WxConstant.WX_APP_ID).replace("SECRET", WxConstant.WX_SECRENT);
                //获取访问用户身份的access_token
                String access_token =  AuthUtil.doGetJson(tokenUrl).get("access_token").toString();
//                log.info("【访问用户身份access_token】,access_token={}",access_token);

                //拼装获取访问用户身份的userid的url请求
                String useridURL = WxConstant.WX_GET_USERID_URL.replace("ACCESS_TOKEN", access_token).replace("CODE", code);
                //获取访问用户身份的基本信息（如userid）
                JSONObject obj=AuthUtil.doGetJson(useridURL);
//                log.info("【访问用户身份基本信息】,obj={}",obj);

                //拼装获取访问用户身份详细信息的url请求
                String userurl = WxConstant.WX_GET_USERINFO_URL.replace("ACCESS_TOKEN", access_token).replace("USERID", obj.getString("UserId"));
                //获取访问用户身份的详细信息
                 userInfo=AuthUtil.doGetJson(userurl);
                System.out.println(userInfo);
//                log.info("【访问用户身份详细信息】,userInfo={}",userInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userInfo;
    }




}